<template>
  <div class="app-container">
    <div class="flex flex-items-start flex-justify-between pb-2px">
      <el-form class="flex-1" ref="searchFormRef" :inline="true" :model="searchData">
        <div>
          <el-form-item prop="username">
            <el-input v-model="searchData.keyword" :placeholder="$t('shop.请输入商品信息') + '...'" clearable />
          </el-form-item>
          <el-form-item prop="phone">
            <!-- <el-date-picker v-model="timeValue" prefix-icon="" type="daterange" :range-separator="$t('common.至')"
              :start-placeholder="$t('common.开始时间')" :end-placeholder="$t('common.结束时间')" format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm" /> -->
              <el-date-picker
        v-model="timeValue"
         :range-separator="$t('common.至')"
        type="datetimerange"
        :start-placeholder="$t('common.开始时间')"
        :end-placeholder="$t('common.结束时间')"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
      />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" round :icon="Search" @click="handleSearch">
              {{ $t('common.搜索') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
      <div>
        <el-button type="info" round class="info-self-btn color-#4E5969 shop_btn" :class="{ active: isMarketing }"
          @click="filterSearch">
          {{ $t('shop.营销商品') }}
        </el-button>
        <el-button type="info" round class="info-self-btn color-#4E5969" @click="handleSetUp('')">
          {{ $t('shop.批量下架') }}
        </el-button>
        <el-button type="primary" class="mr16px" round @click="createGood({}, -1)">{{ $t('shop.新增商品') }}</el-button>
      </div>
    </div>

    <div class="table-wrapper" v-loading="loading">
      <el-table :data="tableData" fixed="left" header-cell-class-name="cell-self-clas" cell-class-name="cell-class-name"
        :row-class-name="tableRowClassName" :row-key="getRowKey" size="large" border
        @selection-change="handleSelectionChange" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column type="selection" width="55px" :selectable="hasSelectable"></el-table-column>
        <el-table-column prop="pic" :label="$t('shop.商品信息')" align="center" fixed min-width="280px">
          <template #default="{ row }">
            <div class="w100 flex flex-content-center flex-items-center shop_wrap">
              <el-image class="w-97px h-76px rounded-10px mr-8px flex-none" :src="row[CL('pic')]" fit="fill"
                :preview-src-list="[row[CL('pic')]]" preview-teleported></el-image>
              <div class="flex-1 text-align-left title">{{ row[CL('name')] || "--" }}</div>
            </div>

          </template>
        </el-table-column>
        <el-table-column prop="sell_price" :label="$t('shop.单价')" align="center" min-width="140px">
          <template #default="{ row }">
            {{row.currency || '￥' }}{{ row['sell_price'] }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" :label="$t('shop.总库存')" align="center" min-width="84px">
          <template #default="{ row }">
            {{ row.stock }}{{ $t('shop.件') }}
          </template>
        </el-table-column>
        <el-table-column prop="createtime" :label="$t('shop.创建时间')" align="center" min-width="170px"> </el-table-column>
        <el-table-column :prop="CL('params')" :label="$t('shop.商品规格')" align="center"
          min-width="100px"></el-table-column>
        <el-table-column :prop="CL('pro_color')" :label="$t('shop.商品颜色')" align="center"
          min-width="110px"></el-table-column>
        <el-table-column prop="gid" :label="$t('shop.营销活动')" align="center" min-width="160px">
          <template #default="{ row }">
            <div class="w100% flex flex-content-center flex-items-center flex-col">
              <el-switch  v-if="row.cname" active-value="4" inactive-value="0"  v-model="row.gid" style="--el-switch-on-color: #13ce66; "
                @click="() => onMarketingChangeStatus(row, true)" />
              <div class="w100% text-align-center font-size-14px color-#1D2129 mb4px" v-show="row.gid === '4'"> {{ $t('good.折扣') }}</div>
              <el-input-number class="w100% my-el-input-number mb8px" size="small" v-model="row.huodong" :step="10"
                :min="10" :max="90" step-strictly @change="activityChange(row)" v-show="row.gid === '4'" />
              <el-button type="primary" round class="primary-self-btn" size="small" @click="activitySubmit(row)"
                v-show="row.isActivity && row.gid === '4'">
                {{ $t('common.确认') }}
              </el-button>
            </div>

          </template>
        </el-table-column>
        <el-table-column prop="zhiding" :label="$t('shop.置顶')" align="center" min-width="100px">
          <template #default="{ row }">
            <div class="w100% text-align-center" v-if="!row.proid">
              <el-switch :active-value="1" :inactive-value="0" v-model="row.zhiding"
                style="--el-switch-on-color: #13ce66; " @click="onSwitchChangeStatus(row)" />
            </div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" :label="$t('common.操作')" width="260px" align="center">
          <template #default="{ row }">
            <div class="w100% flex flex-justify-around flex-items-center flex-wrap pb3px" v-if="!row.proid && !row.offerId">
              <el-button type="primary" round class="mb12px primary-self-btn common_btn" @click="createGood(row, 0)">
                {{ $t('shop.详情') }}
              </el-button>
              <el-button type="info" round class="mb12px info-self-btn common_btn" @click="handleSetUp(row)">
                {{ $t('shop.下架') }}
              </el-button>
              <el-button type="primary" round class="primary-self-btn common_btn" @click="createGood(row, 1)">
                {{ $t('shop.编辑') }}
              </el-button>
              <el-button type="info" round class="info-self-btn common_btn" @click="handleDelete(row)">
                {{ $t('shop.删除') }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pager-wrapper mt-10px">
      <el-pagination :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
        :total="paginationData.total" :page-size="paginationData.pageSize" :current-page="paginationData.currentPage"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

  </div>
</template>


<script lang="ts" setup>
import type { resGoodData } from "@@/apis/good/type"
import { anchorEmits, type FormInstance } from "element-plus"
const router = useRouter()

import { getproductList, updateActivity, topUp, setst, delProduct } from "@@/apis/good"
import { usePagination } from "@@/composables/usePagination"
import { Search } from "@element-plus/icons-vue"
import type { TableColumnCtx } from 'element-plus'

import { inject } from 'vue'

const CL: any = inject("$CL");

import { useI18n } from 'vue-i18n'
const { locale, t } = useI18n()

defineOptions({
  // 命名当前组件
  name: "GoodList"
})
const lang = ref<string>("");
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

let isMarketing = ref<boolean>(false);

// #region 查
const tableData = ref<resGoodData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const timeValue = ref<Array<string>>([])
const statusList = ref([{
  label: t('common.全部'),
  value: -1,
}, {
  label: t('shop.营销商品'),
  value: 0,
}])
const searchData = reactive({
  status: -1,
  ctime: '',
  keyword: '',
})

watch(() => timeValue.value, (val) => {
  if(val){
  searchData.ctime = val.join(' ~ ')
  }else{
    searchData.ctime=''
  }
})

// watch(() => searchData.status, (val) => {
//   // getTableData();
// })

// 筛选
function filterSearch() {
  isMarketing.value = !isMarketing.value;
  getTableData();
}

function getTableData() {
  let obj={
    page: paginationData.currentPage,
    limit: paginationData.pageSize,
    ctime: searchData.ctime,
    keyword: searchData.keyword,
    status: "1",
    gid: isMarketing.value ? "4" : "",
  }

  loading.value = true
  let list=['keyword']
  if(locale.value=='ru'){
          for (let key in obj) {
            list.forEach((item=>{
              if (key === item) {
                obj[key + '_ru'] = obj[key]; // 将值赋给新 key
                delete obj[key];     // 删除旧的 key
              }
            }))
          }
  }
  getproductList(obj).then(({ data }) => {
    paginationData.total = data.count
    tableData.value = data.list.map((item: any) => {
      let obj = {
        ...item,
        oldhuodong: item.huodong,
        isActivity: false,
      }
      return obj;
    });
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}

function getRowKey(row: any) {
  if (row.proid) {
    return (row.proid + "" + row.id);
  } else {
    return (row.id + "first");
  }
}

function hasSelectable(row: any, index: number) {
  return !row.proid;
}

const activityChange = (item: any) => {
  if (item.oldhuodong !== item.huodong) {
    item.isActivity = true;
  } else {
    item.isActivity = false;
  }
}

const activitySubmit = (item: any) => {
  onMarketingChangeStatus(item, false)
}

// 营销活动
const onMarketingChangeStatus = async (val: any, isOpen: boolean = false) => {

  try {
    loading.value = true;
    let gid = "0";
    let proid = "";
    let guigeId = "";
    let activity = "0";
    if (val.gid === true || val.gid === "4") {
      gid = "4";
      activity = !val.huodong || val.huodong === "0" ? "90" : String(val.huodong);
      if (isOpen) activity = "90";
    } else {
      gid = "0";
      activity = "0";
    }
    if (!!val.proid) {
      proid = String(val.proid);
      guigeId = String(val.id);
    } else {
      proid = String(val.id);
      guigeId = "";
    }
    let { code } = await updateActivity({
      proid: proid,
      gid: gid,
      huodong: activity,
      guige_id: guigeId,
    })
    if (code === 1) {
      ElMessage.success(t('common.操作成功'))
    }
    getTableData();
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
}


// 置顶
const onSwitchChangeStatus = async (row: any) => {
  try {
    loading.value = true;
    let { code } = await topUp({
      bid: row.bid,
      id: row.id,
      st: String(row.zhiding || 0),
      locale:locale.value
    })
    ElMessage.success(t('common.操作成功'))
    getTableData()
    loading.value = false;
  } catch (error) {
    getTableData()
    loading.value = false;
  }
}

// #endregion

// #region 编辑

// 商品下架
const handleSetUp = (row: any) => {
  if (selectionList.value.length === 0 && !row) {
    ElMessage.warning(t('shop.请选择要下架的商品'))
    return;
  }
  let ids: Array<Number | String> = [];
  if (!row) {
    toRaw(selectionList.value).forEach((ele) => {
      ids.push(ele.id);
    })
  } else {
    ids = [row.id]
  }

  ElMessageBox.confirm(t('shop.确认下架商品吗？'), t('shop.下架商品'), {
    confirmButtonText: t('common.确认'),
    cancelButtonText: t('common.取消'),
    customClass: "new_box",
    type: "warning"
  }).then(() => {
    setst({
      bid: row.bid,
      status: "0",
      ids: ids.join(','),
    }).then(() => {
      ElMessage.success(t('common.下架成功'))
      getTableData()
    })
  }).catch(() => {

  })
}

// 列表选择
const selectionList = ref<{ id: number }[]>([])

// 删除
function handleDelete(row: resGoodData) {
  ElMessageBox.confirm(t('shop.确认删除商品吗？'), t('shop.删除商品'), {
    confirmButtonText: t('common.确认'),
    cancelButtonText: t('common.取消'),
    customClass: "new_box",
    type: "warning"
  }).then(() => {
    delProduct({
      bid: row.bid,
      ids: String(row.id),
    }).then(() => {
      ElMessage.success(t('common.删除成功'))
      getTableData()
    })
  }).catch(() => {

  })
}

// 新增商品
const createGood = (row: Object, state: number) => {
  router.push({ path: '/good/add-good', query: { id: (row as { id: string | number }).id, state } })
}
const handleSelectionChange = (e: { id: number }[]) => {
  selectionList.value = e;
}
// #endregion

// 表格隔行变色
interface User {
  date: string
  name: string
  address: string
}
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User
  rowIndex: number
}) => {
  if (rowIndex % 2 == 0) {
    return 'primary-row-color'
  } else {
    return 'info-row-color'
  }
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.app-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;

  // 筛选项重置
  .el-form {
    .el-form-item {

      :deep(.el-form-item__content) {
        min-width: 190px;
        .el-date-editor {
          border-radius: 16px;
          background: #F2F3F5;
          box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
        }
      }

      .el-input {
        :deep(.el-input__wrapper) {
          border-radius: 16px;
          box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
          background: #F2F3F5;
        }

      }
    }

  }

  .el-select {
    :deep(.el-select__wrapper) {
      border-radius: 16px;
      background: #007AFF;

      .el-select__placeholder {
        color: #fff;
      }

      .el-select__suffix {
        .el-icon {
          color: #fff;
        }
      }
    }
  }

  .table-wrapper {
    flex: 1;
    overflow: hidden;

    .el-table {
      height: 100%;
      border-top-left-radius: 30px;
      border-top-right-radius: 30px;

      :deep(.cell-self-clas) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
        background: #F2F3F5;
        border-right: none;
      }

      :deep(.cell-class-name) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
      }
    }

  }

  .order-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;

    .left-text {
      color: #1D2129;
      font-size: 14px;
      font-weight: 400;
    }
  }
}

:deep(.dialog-wrapppx) {
  background: linear-gradient(to right, #FBFCFD, #F5F9FD, #ECF6FD);
}

.info-self-btn {
  background: #F2F3F5;
  box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
  color: #1D2129;
  border-color: transparent;

  &:hover {
    box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.3);
    transition: all 0.3s;
  }
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

.my-el-input-number {
  position: relative;
}

.my-el-input-number::after {
  content: '%';
  display: inline-block;
  height: 20px;
  line-height: 20px;
  width: 20px;
  text-align: center;
  position: absolute;
  right: 32px;
  top: 50%;
  font-size: 12px;
  transform: translateY(-50%);
}

.my-el-input-number .el-input__inner {
  padding-left: 30px;
  padding-right: 48px;
}

.common_btn {
  margin-left: 0;
  min-width: 40%;
}

.shop_btn.active {
  background: linear-gradient(139.75deg, #ABE2E7 24.29%, #D8EFF5 53.1%, #F4F7FC 82.49%);
}
</style>
